package com.ohc.leetcode.链表;

/**
 * 2022年4月18日14:21:29
 * https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
 */
public class 删除链表的第n个结点19 {
    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    // head 头结点
    public static ListNode removeNthFromEnd(ListNode head, int n) {
        // 虚拟头结点
        ListNode dumpNode = new ListNode(0, head);
        int length = 0;
        ListNode temp = head;
        while (temp != null) {
            length++;
            temp = temp.next;
        }
        temp = dumpNode;
        if (n > length) {
            return null;
        }
        for (int i = 0; i < length - n; i++) {
            temp = temp.next;
        }
        temp.next = temp.next.next;
        if (n == length) {
            return temp.next;
        } else {
            return head;
        }
    }

    public static void main(String[] args) {
        ListNode node4 = new ListNode(4, null);
        ListNode node3 = new ListNode(3, node4);
        ListNode node2 = new ListNode(2, node3);
        ListNode node1 = new ListNode(1, node2);
        ListNode listNode = removeNthFromEnd(node1, 2);
        while (listNode != null) {
            System.out.println("listNode.val = " + listNode.val);
            listNode = listNode.next;
        }

    }
}
